<template>
  <!-- 搜索 + 列设置 -->
  <a-space
    align="center"
    style="width:100%; justify-content:center; margin-bottom:16px;"
  >
    <a-form :model="formSearchParams" layout="inline" @submit="doSearch">
      <a-form-item field="resultName" label="结果名称">
        <a-input
          v-model="formSearchParams.resultName"
          placeholder="请输入结果名称"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="resultDesc" label="结果描述">
        <a-input
          v-model="formSearchParams.resultDesc"
          placeholder="请输入结果描述"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="appId" label="测评活动 id">
        <a-input
          v-model="formSearchParams.appId"
          placeholder="请输入测评活动 id"
          allow-clear
        />
      </a-form-item>
      <div class="form-break"></div>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-popover trigger="click" title="选择要展示的列">
            <template #content>
              <a-checkbox-group
                v-model="selectedKeys"
                :options="columnOptions"
              />
            </template>
            <a-button>列设置</a-button>
          </a-popover>
        </a-space>
      </a-form-item>
    </a-form>
  </a-space>

  <!-- 表格 -->
  <a-table
    :columns="visibleColumns"
    :data="dataList"
    :pagination="{
      showTotal: true,
      pageSize: searchParams.pageSize,
      current: searchParams.current,
      total,
    }"
    @page-change="onPageChange"
  >
    <template #resultPicture="{ record }">
      <a-image width="64" :src="record.resultPicture" />
    </template>
    <template #appType="{ record }">
      {{ APP_TYPE_MAP[record.appType] }}
    </template>
    <template #scoringStrategy="{ record }">
      {{ APP_SCORING_STRATEGY_MAP[record.scoringStrategy] }}
    </template>
    <template #createTime="{ record }">
      {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
    </template>
    <template #updateTime="{ record }">
      {{ dayjs(record.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
    </template>
    <template #optional="{ record }">
      <a-space>
        <a-button status="danger" @click="doDelete(record)">删除</a-button>
      </a-space>
    </template>
  </a-table>
</template>

<script setup lang="ts">
import { ref, watchEffect, computed } from "vue";
import {
  listMyUserAnswerVoByPageUsingPost,
  deleteUserAnswerUsingPost,
} from "@/api/userAnswerController";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import type { CheckboxOption } from "@arco-design/web-vue";
import { APP_SCORING_STRATEGY_MAP, APP_TYPE_MAP } from "@/constant/app";

// 所有可选列定义
interface ColDef {
  key: string;
  title: string;
  dataIndex?: string;
  slotName?: string;
}
const allColumns: ColDef[] = [
  { key: "id",              title: "ID",               dataIndex: "id" },
  { key: "choices",         title: "选项",             dataIndex: "choices" },
  { key: "resultId",        title: "结果 ID",          dataIndex: "resultId" },
  { key: "resultName",      title: "名称",             dataIndex: "resultName" },
  { key: "resultDesc",      title: "描述",             dataIndex: "resultDesc" },
  { key: "resultPicture",   title: "图片",             dataIndex: "resultPicture", slotName: "resultPicture" },
  { key: "resultScore",     title: "得分",             dataIndex: "resultScore" },
  { key: "appId",           title: "测评活动 ID",       dataIndex: "appId" },
  { key: "appType",         title: "测评活动类型",     dataIndex: "appType",         slotName: "appType" },
  { key: "scoringStrategy", title: "评分策略",         dataIndex: "scoringStrategy", slotName: "scoringStrategy" },
  { key: "createTime",      title: "创建时间",         dataIndex: "createTime",      slotName: "createTime" },
  { key: "updateTime",      title: "更新时间",         dataIndex: "updateTime",      slotName: "updateTime" },
  { key: "optional",        title: "操作",             slotName: "optional" },
];

// 默认展示的列 keys
const defaultKeys = ["choices", "resultName", "resultScore", "createTime", "optional"];
const selectedKeys = ref<string[]>([...defaultKeys]);

// 用于复选框的列选项
const columnOptions = computed<CheckboxOption[]>(() =>
  allColumns.map((col) => ({ label: col.title, value: col.key }))
);

// 根据 selectedKeys 计算实际要传给 <a-table> 的 columns
const visibleColumns = computed(() =>
  allColumns
    .filter((col) => selectedKeys.value.includes(col.key))
    .map((col) => {
      const c: any = { title: col.title, key: col.key };
      if (col.dataIndex) c.dataIndex = col.dataIndex;
      if (col.slotName) c.slotName = col.slotName;
      return c;
    })
);

// 搜索 & 分页相关状态
const formSearchParams = ref<Partial<API.UserAnswerQueryRequest>>({});
const initSearchParams = { current: 1, pageSize: 10 };
const searchParams = ref<Partial<API.UserAnswerQueryRequest>>({ ...initSearchParams });
const dataList = ref<API.UserAnswerVO[]>([]);
const total = ref(0);

// 加载数据
async function loadData() {
  const res = await listMyUserAnswerVoByPageUsingPost(searchParams.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
  } else {
    message.error("获取数据失败：" + res.data.message);
  }
}

// 执行搜索
function doSearch() {
  searchParams.value = { ...initSearchParams, ...formSearchParams.value };
}

// 分页变化
function onPageChange(page: number) {
  searchParams.value = { ...searchParams.value, current: page };
}

// 删除
async function doDelete(record: API.UserAnswerVO) {
  if (!record.id) return;
  const res = await deleteUserAnswerUsingPost({ id: record.id });
  if (res.data.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除失败：" + res.data.message);
  }
}

// 监听并加载
watchEffect(loadData);
</script>
<style scoped>
.form-break {
  flex-basis: 100%;
  height: 0;
  margin: 0;
  padding: 0;
}
</style>